package com.briup.service.impl;

import com.briup.bean.Customer;
import com.briup.dao.CustomerMapper;
import com.briup.service.ICustomerService;
import com.briup.util.MyBatisSqlSessionFactory;
import org.apache.ibatis.session.SqlSession;

public class ICustomerServiceImpl implements ICustomerService {

    private CustomerMapper customerMapper;
    private SqlSession sqlSession;

    {
        sqlSession = MyBatisSqlSessionFactory.openSession();
        customerMapper = sqlSession.getMapper(CustomerMapper.class);
    }

    @Override
    public void register(Customer customer) {
        //注册业务逻辑处理：用户名不存在
        String name = customer.getName();
        if (name == null || name.trim().equals("")) {
            throw new RuntimeException("用户名不合规范！");
        }

        //注册业务逻辑处理：用户存在
        Customer customerByDB = findCustomerByName(customer.getName());
        if (customerByDB != null) {
            throw new RuntimeException("用户已经存在！");
        }

        //插入到数据库中
        customerMapper.saveCustomer(customer);
    }

    @Override
    public Customer findCustomerByName(String name) {
        //调用dao层
        return customerMapper.findCustomerByName(name);
    }

    @Override
    public Customer login(String userName, String userPassword) {
        Customer customerByDB = customerMapper.findCustomerByName(userName);
        if (customerByDB != null) {
            String passwordDB = customerByDB.getPassword();
            if (userPassword.equals(passwordDB) && !userPassword.trim().equals("")) {
                return customerByDB;
            } else {
                return null;
                //throw new RuntimeException("用户密码不正确！");
            }
        } else {
            return null;
            //throw new RuntimeException("用户名不存在！");
        }
    }
}